﻿
namespace EveKillboard
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Core;

    public class EveFittingFormatter
    {
        public static string Format(Killmail killmail)
        {
            var sb = new StringBuilder();
            sb.AppendFormat("javascript:CCPEVE.showFitting('{0}", killmail.Destroyed.Id);

            AppendItems(killmail.ItemsFittedSubSlot, sb);
            AppendItems(killmail.ItemsFittedHighSlot, sb);
            AppendItems(killmail.ItemsFittedMedSlot, sb);
            AppendItems(killmail.ItemsFittedLowSlot, sb);
            AppendItems(killmail.ItemsFittedRigSlot, sb);

            sb.Append("::')");
            return sb.ToString();
        }

        static void AppendItems(IEnumerable<KillmailItem> items, StringBuilder sb)
        {
            foreach (var item in items.GroupBy(i => i.Item.Id))
                sb.AppendFormat(":{0};{1}", item.Key, GetQuantity(item.Key, items));
        }

        static int GetQuantity(int itemId, IEnumerable<KillmailItem> items)
        {
            return items.Where(i => i.Item.Id == itemId).Sum(i => i.Quantity);
        }
    }
}